package com.zzsz.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.zzsz.common.annotation.Anonymous;
import com.zzsz.common.core.controller.BaseController;
import com.zzsz.common.core.domain.AjaxResult;
import com.zzsz.domain.RecipientQueryDTO;
import com.zzsz.domain.WaringRecipient;
import com.zzsz.service.RecipientService;
import com.github.pagehelper.PageInfo;
import com.zzsz.utils.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * --- 这有何难 ---
 * ƪ(˘⌣˘)ʃ
 *
 * @author 超级无敌张恒阳大王
 * @date 4/9/2025
 * @desc
 */
@Slf4j
@RestController
@RequestMapping("/recipient")
public class RecipientController extends BaseController {

	@Autowired
	private RecipientService recipientService;
	@Autowired
	private AliyunOSSOperator aliyunOSSOperator;
	/**
	 * 查找全部预警接收人
	 *
	 * @return 预警接收人列表
	 */
	@GetMapping("/list")
	public AjaxResult getRecipientList(RecipientQueryDTO recipientQueryDTO) {
		PageInfo<WaringRecipient> recipientPageInfo = recipientService.getRecipientList(recipientQueryDTO);
		log.debug("recipientPageInfo:{}", recipientPageInfo);
		return AjaxResult.success(recipientPageInfo);
	}

	/**
	 * 添加预警接收人
	 * @param waringRecipient 预警接收人信息
	 * @return 操作结果
	 */
	@PostMapping
	public AjaxResult addRecipient(@RequestBody WaringRecipient waringRecipient) {
		int result = recipientService.addRecipient(waringRecipient);
		if (result > 0) {
			return AjaxResult.success("添加成功");
		} else {
			return AjaxResult.error("添加失败");
		}
	}

	/**
	 * 更新预警接收人
	 * @param recipientId 接收人ID
	 * @param waringRecipient 预警接收人信息
	 * @return 操作结果
	 */
	@PutMapping("/{recipientId}")
	public AjaxResult updateRecipient(@PathVariable Integer recipientId, @RequestBody WaringRecipient waringRecipient) {
		// 确保更新的是正确的接收人
		waringRecipient.setRecipientId(recipientId);
		int result = recipientService.updateRecipient(waringRecipient);
		if (result > 0) {
			return AjaxResult.success("更新成功");
		} else {
			return AjaxResult.error("更新失败");
		}
	}

	/**
	 * 删除预警接收人
	 * @param recipientId 接收人ID
	 * @return 操作结果
	 */
	@DeleteMapping("/{recipientId}")
	public AjaxResult deleteRecipient(@PathVariable Integer recipientId) {
		int result = recipientService.deleteRecipient(recipientId);
		if (result > 0) {
			return AjaxResult.success("删除成功");
		} else {
			return AjaxResult.error("删除失败");
		}
	}

	/**
	 * 导出预警接收人列表为Excel
	 * @param recipientQueryDTO 查询条件
	 * @param response HTTP响应
	 */
	@GetMapping("/export")
	public void exportRecipientList(RecipientQueryDTO recipientQueryDTO, HttpServletResponse response) {
		try {
			// 1. 获取所有符合条件的接收人数据
			List<WaringRecipient> recipientList = recipientService.getAllRecipientList(recipientQueryDTO);
			log.info("导出预警接收人列表，共{}条数据", recipientList.size());

			// 2. 设置响应头，告诉浏览器这是一个下载文件
			response.setContentType("application/vnd.ms-excel");
			response.setCharacterEncoding("UTF-8");
			// 生成文件名，包含当前日期
			String fileName = "预警接收人列表_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xlsx";
			// URL编码，防止中文乱码
			String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%");
			response.setHeader("Content-disposition", "attachment;filename=" + encodedFileName);

			// 3. 创建EasyExcel的写入样式策略
			// 头的策略
			WriteCellStyle headWriteCellStyle = new WriteCellStyle();
			// 设置头背景色
			headWriteCellStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
			// 设置头字体
			WriteFont headWriteFont = new WriteFont();
			headWriteFont.setFontHeightInPoints((short)20);
			headWriteFont.setBold(true);
			headWriteCellStyle.setWriteFont(headWriteFont);
			// 内容的策略
			WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
			// 设置内容背景色
			contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
			// 设置内容字体
			WriteFont contentWriteFont = new WriteFont();
			contentWriteFont.setFontHeightInPoints((short)14);
			contentWriteCellStyle.setWriteFont(contentWriteFont);
			// 应用策略
			HorizontalCellStyleStrategy styleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

			// 4. 使用EasyExcel写入数据到响应流
			EasyExcel.write(response.getOutputStream(), WaringRecipient.class)
					.registerWriteHandler(styleStrategy)
					.sheet("预警接收人列表")
					.doWrite(recipientList);
		} catch (Exception e) {
			log.error("导出预警接收人列表失败", e);
			// 如果导出失败，设置响应状态为500
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			try {
				response.getWriter().write("导出失败：" + e.getMessage());
			} catch (IOException ex) {
				log.error("写入错误信息失败", ex);
			}
		}
	}

	/**
	 * 上传文件
	 * @param file 上传的文件
	 * @return 上传结果
	 */
	@Anonymous
	@PostMapping("/upload")
	public AjaxResult upload(MultipartFile file) throws Exception {
		log.info("上传文件：{}", file);
		if (!file.isEmpty()) {
			// 生成唯一文件名
			String originalFilename = file.getOriginalFilename();
			String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
			String uniqueFileName = UUID.randomUUID().toString().replace("-", "") + extName;
			// 上传文件
			String url = aliyunOSSOperator.upload(file.getBytes(), uniqueFileName);
			Map<String, String> result = new HashMap<>();
			result.put("url", url);
			return AjaxResult.success(result);
		}
		return AjaxResult.error("上传失败");
	}


	/**
	 * 导入预警接收人数据
	 * @param file Excel文件
	 * @return 导入结果
	 */
	@PostMapping("/import")
	public AjaxResult importRecipient(@RequestParam("file") MultipartFile file) {
		try {
			log.info("开始导入预警接收人数据");
			int result = recipientService.importRecipientData(file);
			return AjaxResult.success("导入成功，共导入" + result + "条数据");
		} catch (Exception e) {
			log.error("导入预警接收人数据失败", e);
			return AjaxResult.error("导入失败：" + e.getMessage());
		}
	}

	/**
	 * 下载Excel模板
	 * @param response HTTP响应
	 */
	@GetMapping("/import/template")
	public void importTemplate(HttpServletResponse response) {
		try {
			log.info("下载预警接收人导入模板");

			// 设置响应头
			response.setContentType("application/vnd.ms-excel");
			response.setCharacterEncoding("UTF-8");
			String fileName = "预警接收人导入模板.xlsx";
			String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%");
			response.setHeader("Content-disposition", "attachment;filename=" + encodedFileName);

			// 创建样式策略
			WriteCellStyle headWriteCellStyle = new WriteCellStyle();
			headWriteCellStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
			WriteFont headWriteFont = new WriteFont();
			headWriteFont.setFontHeightInPoints((short)20);
			headWriteFont.setBold(true);
			headWriteCellStyle.setWriteFont(headWriteFont);

			WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
			contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
			WriteFont contentWriteFont = new WriteFont();
			contentWriteFont.setFontHeightInPoints((short)14);
			contentWriteCellStyle.setWriteFont(contentWriteFont);

			HorizontalCellStyleStrategy styleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

			// 创建一个空的模板数据
			List<WaringRecipient> templateData = new ArrayList<>();
			templateData.add(new WaringRecipient()); // 添加一行空数据作为模板

			// 写入Excel
			EasyExcel.write(response.getOutputStream(), WaringRecipient.class)
					.registerWriteHandler(styleStrategy)
					.sheet("预警接收人模板")
					.doWrite(templateData);
		} catch (Exception e) {
			log.error("下载模板失败", e);
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			try {
				response.getWriter().write("下载模板失败：" + e.getMessage());
			} catch (IOException ex) {
				log.error("写入错误信息失败", ex);
			}
		}
	}


}